#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# QcmLineEdit Copyright (C) 2009  Chris Marsh
# Version 0.2.0
#
# Currency Converter is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
#
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# *********************************************************************************
# Original C++ code Copyright (c) 2007 Trolltech ASA <info@trolltech.com>
# *********************************************************************************

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import QcmLineEdit_rc

class QcmLineEdit(QLineEdit):
        
    def __init__(self, parent = None):
        super(QcmLineEdit, self).__init__(parent)
        
        self.clearButton = QToolButton(self)
        pixmap=QPixmap(":/clear.png")
        self.clearButton.setIcon(QIcon(pixmap))
        self.clearButton.setIconSize(pixmap.size())
        self.clearButton.setCursor(Qt.ArrowCursor)
        self.clearButton.setToolTip("Clear text")
        self.clearButton.setStyleSheet("QToolButton {border: none; padding-top: 2px; padding-bottom: 2px; padding-right: 4px;}")
        self.clearButton.hide()
        
        frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
        self.setStyleSheet("QLineEdit { padding-right: %spx;}" % (self.clearButton.sizeHint().width() + frameWidth - 2))
        msz = self.minimumSizeHint()
        self.setMinimumSize(max(msz.width(), self.clearButton.sizeHint().width() + frameWidth * 2 + 2),
                       max(msz.height(), self.clearButton.sizeHint().height() + frameWidth * 2 + 2))
        
        self.connect(self.clearButton, SIGNAL("clicked()"), self.clear)
        self.connect(self, SIGNAL("textChanged(const QString&)"), self.updateClearButton)

    def resizeEvent(self,  evt):
        sz = self.clearButton.sizeHint()
        frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
        self.clearButton.move(self.rect().right() - frameWidth - sz.width(), (self.rect().bottom() + 1 - sz.height())/2)

    def updateClearButton(self,  text):
        self.clearButton.setVisible(not text.isEmpty())

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = QcmLineEdit()
    form.show()
    sys.exit(app.exec_())
